package com.iscas.green.extralindextest.servlet;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 请求日志过滤器
 * 使用WebFilter注解注册，拦截所有servlet路径的请求
 */
@WebFilter(urlPatterns = "/servlet/*")
public class LoggingFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(LoggingFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("LoggingFilter初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestURI = httpRequest.getRequestURI();
        String method = httpRequest.getMethod();
        
        long startTime = System.currentTimeMillis();
        log.info("开始处理请求: {} {}", method, requestURI);
        
        try {
            // 继续执行过滤器链
            chain.doFilter(request, response);
        } finally {
            long duration = System.currentTimeMillis() - startTime;
            log.info("请求处理完成: {} {} - 耗时: {}ms", method, requestURI, duration);
        }
    }

    @Override
    public void destroy() {
        log.info("LoggingFilter销毁");
    }
} 